package com.vayne.thread;

/**
 * @author xuerui.zhang
 * @since 2020/4/25 下午7:40
 */
public class WaitAndNotifyDemo {

    public static void main(String[] args) throws InterruptedException {
        Object lock = new Object();
        new ThreadWaitAndNotifyA(lock).start();
        Thread.sleep(500);
        new ThreadWaitAndNotifyB(lock).start();
    }
}

class ThreadWaitAndNotifyA extends Thread {

    private Object lock;

    public ThreadWaitAndNotifyA(Object object) {
        this.lock = object;
    }

    @Override
    public void run() {
        try {
            synchronized (lock) {
                if (MyList.size() != 5) {
                    System.out.println("start wait");
                    lock.wait();
                    System.out.println("end wait");
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ThreadWaitAndNotifyB extends Thread {

    private Object lock;

    public ThreadWaitAndNotifyB(Object object) {
        this.lock = object;
    }

    @Override
    public void run() {
        try {
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    MyList.add();
                    if (MyList.size() == 5) {
                        // 唤醒后并不会立即放弃执行权
                        lock.notify();
                        System.out.println("send notify");
                    }
                    System.out.println("已添加了 " + (i + 1) + " 个元素");
                    Thread.sleep(1000);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}